package com.turing.draw.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.turing.common.response.ResponseCode;
import com.turing.common.response.ResponseMessage;
import com.turing.common.response.ResponseVO;
import com.turing.common.util.*;
import com.turing.draw.model.domain.FileImage;
import com.turing.draw.model.domain.OcrPageTask;
import com.turing.draw.model.vo.in.OcrResultVo;
import com.turing.draw.enums.FileStatusEnum;
import com.turing.draw.enums.OcrPageTaskStatusEnum;
import com.turing.draw.service.FileImageService;
import com.turing.draw.service.OcrPageTaskService;
import com.turing.draw.task.MergeOcrResultTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("ocrPageTask")
public class OcrPageTaskController {

    private Log logger = LogFactory.getLog(OcrPageTaskController.class);

    /**
     * 合并场景ID
     */
    private static final String MERGE_TEMPLATE_ID = "NB2_OCR_BIAOZHUN";

    /**
     * 非标合并场景ID
     */
    private static final String MERGE_NON_STANDARD_TEMPLATE_ID = "NB2_OCR_FEIBIAO";

    @Autowired
    private OcrPageTaskService ocrPageTaskService;

    @Autowired
    private FileImageService fileImageService;

    @Autowired
    private MergeOcrResultTask mergeOcrResultTask;

    @PostMapping("getAndLockOcrPageTask")
    @Transactional
    public ResponseVO<OcrPageTask> getAndLockOcrPageTask( @RequestParam("domain") String domain ){

        OcrPageTask ocrPageTask = ocrPageTaskService.getOcrPageTask();

        if( ocrPageTask != null ){
            ocrPageTaskService.lockOcrPageTask( ocrPageTask.getOcrPageTaskSn(), domain );
        }
        return ResponseUtil.success(ocrPageTask);

    }

    @PostMapping("unLockOcrPageTask")
    public ResponseVO<Object> unLockOcrPageTask( @RequestParam("ocrPageTaskSn") String ocrPageTaskSn ){
        logger.info("unLockOcrPageTask..");
        return ResponseUtil.success(ocrPageTaskService.unLockOcrPageTask(ocrPageTaskSn));
    }

    @PostMapping("ocrResultCallback")
    @Transactional(propagation = Propagation.REQUIRED)
    public ResponseVO<Object> ocrResultCallback( @RequestBody OcrResultVo ocrResultVo ){

        String ocrPageTaskSn = ocrResultVo.getOcrPageTaskSn();
        Integer taskStatus = ocrPageTaskService.getTaskStatusById(ocrPageTaskSn);

        if(taskStatus.equals(FileStatusEnum.NOTEXIST.getCode()) ){
            logger.info("call back ocr page task failed,ocrPageTaskSn is:"+ocrResultVo.getOcrPageTaskSn());
            return new ResponseVO<>(ResponseCode.TASK_NULL, ResponseMessage.TASK_NULL);
        }

        boolean isOcrAllComplete = false;
        // avoid update duplicate
        if(!taskStatus.equals(OcrPageTaskStatusEnum.OCRTASKFINISHED.getCode())){

            // ocr result, update file task result also
            logger.info("写入文件信息");
            boolean update = ocrPageTaskService.saveJSONResult(ocrResultVo.getJSONUrl(), ocrPageTaskSn);

            logger.info("update ocr page task,result is:"+update);

            String taskSn = ocrResultVo.getTaskSn();
            Integer pageNo = ocrResultVo.getPageNo();
            String imageUrl = ocrResultVo.getImageUrl();
            Integer imgWidth = ocrResultVo.getImgWidth();
            Integer imgHeight = ocrResultVo.getImgHeight();

            FileImage fileImage = fileImageService.getFileImageByPage(taskSn,pageNo);


            // delete original file in fdfs
            if(fileImage != null && !StringUtils.isEmpty(fileImage.getImageUrl())){
                try{
                    // sweep mid photos
                    //FdfsUtils.delete_file(fileImage.getImageUrl());
                    // save image
                    boolean save = fileImageService.updateFileImage(taskSn, pageNo, imageUrl,imgWidth,imgHeight);
                    logger.info("update file image,replace with new image,taskSn is"+taskSn+",pageNo is:"+pageNo + ":,result is:"+save);
                    boolean isMergeTemplate = MERGE_TEMPLATE_ID.equals(ocrResultVo.getTemplateId()) ||
                            MERGE_NON_STANDARD_TEMPLATE_ID.equals(ocrResultVo.getTemplateId());
                    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<是否属于混合场景 isMergeTemplate：" + isMergeTemplate);
                    isOcrAllComplete = mergeOcrResultTask.doMerge(ocrResultVo, isMergeTemplate);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        logger.info("isOcrAllComplete : "  + isOcrAllComplete);
        // 判断为合并场景，检查新增子任务
        String templateId = ocrResultVo.getTemplateId();
        boolean isMergeTemplate = MERGE_TEMPLATE_ID.equals(templateId) || MERGE_NON_STANDARD_TEMPLATE_ID.equals(templateId);
        if (isMergeTemplate && isOcrAllComplete) {
            logger.info("**********开始处理合并场景**********");
            if(TransactionSynchronizationManager.isActualTransactionActive()) {
                // 当前存在事务
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    // 事务提交后执行后处理
                    @Override
                    public void afterCommit() {
                        logger.info("**********afterCommit**********");
                        ocrPageTaskService.checkAndDivisionTemplate(ocrResultVo.getTaskSn(), ocrResultVo.getTemplateId());
                        logger.info("**********合并场景完成**********");
                    }});
            } else {
                logger.info("**********afterCommit else **********");
                ocrPageTaskService.checkAndDivisionTemplate(ocrResultVo.getTaskSn(), ocrResultVo.getTemplateId());
                logger.info("**********合并场景完成**********");
            }

        }

        return ResponseUtil.success();

    }

    public static void main(String[] args) {

        String s = FileUtils.loadJson("http://192.168.1.73:7003/group1/M00/00/DA/wKgBSWIu7GKACSGbAGyqKzoqhLY48.json");
        JSONArray jsonArray = JSONArray.parseArray(s);
        jsonArray.forEach(
                j->{
                    JSONObject jsonObject = JSONObject.parseObject(j.toString());
                    //System.out.println(jsonObject);
                }
        );

    }


}
